<template>
    <div style="position: relative;height: 100%;" class="forbid-select console-page">
        <el-tabs v-model="activeTab" type="border-card" ref="tabRef" v-loading="fillLoading" class="task">
            <el-tab-pane label="基础信息" name="fix-baseInfo">
                <baseInfo :type="type" ref="baseRef" />
            </el-tab-pane>
            <el-tab-pane :label="type.toUpperCase()" name="fix-common" v-if="type">
                <workflow ref="workflowRef" :activeTab="activeTab" />
            </el-tab-pane>
            <el-tab-pane label="参数信息" name="fix-params">
                <params :type="type" ref="paramsRef" />
            </el-tab-pane>
            <el-tab-pane label="周期信息" name="fix-cycle">
                <cycleInfo ref="cycleRef" :type="type" />
            </el-tab-pane>
            <el-tab-pane label="日志信息" name="fix-log" v-if="!newTask">
                <taskLogList fromJob />
            </el-tab-pane>
        </el-tabs>
        <div class="tools">
            <!--<el-button size="mini" icon="el-icon-close" plain>删除</el-button>-->
            <el-button :icon="getIcon('check')" plain @click="save" v-permission="$permission.Update">保存</el-button>
            <el-button :icon="getIcon('promotion')" plain @click="runTask" v-show="!newTask"
                v-permission="$permission.Execute">执行</el-button>
        </div>

        <el-drawer v-model="showDupTask" direction="rtl" :show-close="false" :close-on-press-escape="false"
            :with-header="false" class="task-drawer" append-to-body>
            <template #header>
                <el-row>
                    <el-col :span="24">
                        <div style="font-family: inherit;font-size: 20px;text-align: center">
                            重复节点信息
                        </div>
                    </el-col>
                </el-row>
            </template>
            <div v-for="key in Object.keys(dupTask)">
                <p style="color: #8cc5ff">{{ '节点名称:' + key }}</p>
                <ol>
                    <li v-for="val in dupTask[key]" style="color: #dd6161;padding: 5px;">{{ val }}</li>
                </ol>
            </div>
        </el-drawer>
    </div>
</template>

<script setup>
import router from "@/router"
import taskLogList from "@/views/Task/TaskLogList"
import { useElMessage, useTabPaneAnimation, useRipple, useModalSize, useRequest, useEventListener } from "@usehook"
import { getGlueType } from "@/utils/constant"
import { deepCopy, getIcon } from "@/utils/tools"
import showRunOnce from "@/components/task"
import storeInstance from "@/pinia"

//获取周期信息ref对象
const cycleRef = $ref(null)
//获取基础信息ref对象
const baseRef = $ref(null)
const workflowRef = $ref(null)
const paramsRef = $ref(null)
// 执行器组
let jobGroup = $ref([])
let route = router.currentRoute.value
let fillLoading = $ref(false)
// 任务类型
let type = $ref(route.path.split('/').reverse()[0])
let data = $ref({ glueSource: "", glueParams: {}, db: {} })
let showDupTask = $ref(false)
let dupTask = $ref({})
let activeTab = $ref("fix-baseInfo")
useTabPaneAnimation(() => activeTab, (pane) => { storeInstance.tagMenuStore.setTabPane(pane) })
let agentList = $ref([])

watch(() => showDupTask, status => {
    useModalSize(status)
})

const runTask = () => {
    showRunOnce({ show: true, jobId: parseInt(router.currentRoute.value.query.id), agentList })
}

const newTask = $computed(() => {
    return !route.query.id
})

const save = () => {
    validate().then(result => {
        if (result.check) {
            const workflowData = workflowRef.save()
            const { workflow, orig } = workflowData
            // const params = { ...glueParams, params: paramsRef.parseParams(glueSource) }
            // data.glueParams.params = params.params
            let task = { ...baseRef.save(), ...cycleRef.save(), workflow: JSON.stringify(workflow), orig: JSON.stringify(orig) }

            task['scheduleType'] = 'CRON'
            if (route.query.id) {
                task['id'] = route.query.id
            } else {
                task['glueType'] = getGlueType(type)
            }
            fillLoading = true

            useRequest({
                url: newTask ? "/jobinfo/addWorkflow" : "/jobinfo/updateWorkflow", method: "post", force: showDupTask, ...task
            }).then((resData) => {
                if (resData && resData.status) {
                    const id = newTask ? resData.data : task.id
                    const index = router.currentRoute.value.path + "?id=" + id
                    storeInstance.tagMenuStore.updateTagMenuTitle(router.currentRoute.value.fullPath, task.jobDesc, index)
                    task.id = id
                    useElMessage("保存成功")
                    showDupTask = false
                    if (newTask) router.push(index)
                } else {
                    if (resData.message === 'Cron非法') {
                        activeTab = 'fix-cycle'
                    } else if (resData.message === "组件重复") {
                        dupTask = resData.data
                        showDupTask = true
                    } else {
                        if (resData.message) useElMessage.error(resData.message)
                    }
                }
            }).finally(() => {
                fillLoading = false
            })
        } else {
            activeTab = result.tabs
        }
    })
}

const validate = async () => {
    let checkPass = true
    let tabs = ""

    await baseRef.validate().then(pass => {
        if (pass !== true) {
            checkPass = false
            tabs = "fix-baseInfo"
        }
    })

    if (!checkPass) return { check: checkPass, tabs: tabs }

    await workflowRef.validate().then(pass => {
        if (pass !== true) {
            checkPass = false
            tabs = "fix-common"
        }
    })

    if (!checkPass) return { check: checkPass, tabs: tabs }

    await cycleRef.validate().then(pass => {
        if (pass !== true) {
            checkPass = false
            tabs = "fix-cycle"
        }
    })

    if (!checkPass) return { check: checkPass, tabs: tabs }

    // paramsRef.parseParams((workflowRef.save() || {}).glueSource)
    await paramsRef.validate().then(pass => {
        if (pass !== true) {
            checkPass = false
            tabs = "fix-params"
        }
    })

    return { check: checkPass, tabs: tabs }
}

const fill = (data, provider, dependWorkflow) => {
    if (data) {
        let baseInfo = {
            jobDesc: data.jobDesc,
            alarmEmail: data.alarmEmail,
            author: data.author,
            executorHandler: data.executorHandler
        }
        baseRef.fill(baseInfo)

        let cycle = {
            executorRouteStrategy: data.executorRouteStrategy,
            jobGroup: data.jobGroup,
            executorBlockStrategy: data.executorBlockStrategy,
            misfireStrategy: data.misfireStrategy,
            executorFailRetryCount: data.executorFailRetryCount,
            executorTimeout: data.executorTimeout,
            scheduleConf: data.scheduleConf,
            triggerStatus: data.triggerStatus
        }

        nextTick(() => {
            cycleRef.fill(cycle, provider, dependWorkflow)
        })
    } else {
        nextTick(() => {
            cycleRef.fill(null, provider, dependWorkflow)
        })
    }
}

const getCommonInfo = (params) => {
    fillLoading = true
    useRequest(params).then(resData => {
        if (resData && resData.status) {
            let _data = resData.data.job
            data.glueSource = _data.glueSource
            data.glueParams = JSON.parse(_data.glueParams) || {}
            fill(_data, null, resData.data.dependWorkflow)
            workflowRef.fill(data)
            paramsRef.fill(deepCopy(data.glueParams.params))
        }
    }).finally(() => {
        fillLoading = false
    })
}

onMounted(async () => {
    //加载执行器信息
    useRequest('/jobgroup/getPageData').then((resp) => {
        if (resp && resp.data) {
            for (let agent of resp.data) {
                jobGroup.push({ label: agent.title, value: agent.id })
                for (const agentAddress of agent.registryList) {
                    agentList.push({ title: agent.title, appName: agent.appName, address: agentAddress })
                }
            }
            nextTick(() => {
                cycleRef.fill(null, jobGroup, null)
            })
        }
    })

    //加载数据库连接信息
    if (type === "sql") {
        useRequest({ url: "/data/connection/getConnection" }).then(resData => {
            if (resData && resData.status) {
                data.db = resData.data.db
                workflowRef.fill(data)
                paramsRef.fill(null, data.db)
            } else {
                useElMessage.error("数据库连接信息获取失败")
            }
        })

    }

    if (route.query.id) {
        getCommonInfo({ url: '/jobinfo/job', id: route.query.id })
    }
})

useRipple(".el-tabs__item")

const keyMap = (e) => {
    const { key, ctrlKey, metaKey } = e
    if (key === 's' && (ctrlKey || metaKey)) {
        e.preventDefault()
        save()
    }
}

useEventListener('keydown', keyMap)
</script>

<style scoped>
:deep(#tab-sql .el-tabs__content) {
    padding: 0 !important;
}

/*隐藏非sheet的关闭按钮*/
/*:deep(#tab-fix-baseInfo .el-icon-close,*/
/*:deep(#tab-fix-cycle .el-icon-close,*/
/*:deep(#tab-fix-log .el-icon-close,*/
/*:deep(#tab-add .el-icon-close {*/
/*  padding: 0;*/
/*  display: none;*/
/*  opacity: 0;*/
/*  width: 0;*/
/*}*/

/*表单样式*/
:deep([id*='fix-'] .el-form-item label) {
    line-height: calc(var(--font-size) * 2 - 3px);
    font-size: var(--font-size);
}

:deep(.el-form-item__content) {
    line-height: 25px;
}

:deep(.el-form-item__error) {
    padding-top: 1px;
}

/*!*错误提示信息位置*!*/
:deep(.el-form .el-form-item__error) {
    top: 26%;
    right: 10px;
    left: unset;
    font-size: calc(var(--font-size) - 4px);
    pointer-events: none;
}

/*!*text-area错误提示位置*!*/
/*:deep(.el-form .area-input .el-form-item__error {*/
/*  top: 2% !important;*/
/*  right: -25% !important;*/
/*  left: unset;*/
/*}*/

:deep([id*='pane-Sheet'] .el-form .sheet-name .el-form-item__error) {
    top: 25%;
    right: 5%;
    left: unset;
}

:deep([id*='pane-Sheet'] .el-form .db-info .el-form-item__error) {
    top: 25%;
    right: -20%;
    left: unset;
}

:deep([id*='pane-Sheet']) {
    margin-top: -5px;
}

:deep(.ace_editor) {
    margin-top: 0;
}

:deep(.el-message.is-closable .el-message__content) {
    padding-right: 25px !important;
}

:deep(.tools) {
    position: absolute;
    right: 5px;
    top: 8px;
}

:deep(.tools .el-button) {
    font-family: var(--font-family);
    font-weight: var(--font-weight);
}

:deep(.el-button [class*=el-icon-] + span) {
    margin-left: 1px;
}

:deep(.el-select .el-input.is-focus .el-input__inner) {
    -moz-user-select: none !important;
    /*火狐*/
    -webkit-user-select: none !important;
    /*webkit浏览器*/
    -ms-user-select: none !important;
    /*IE10*/
    -khtml-user-select: none !important;
    /*早期浏览器*/
    user-select: none !important;
}
</style>

<style>
.task-drawer .el-drawer__body {
    padding: 10px;
}
</style>